<?php
	// On prolonge la session
	session_start();

	$id_anim='';
	$code='';
	$message='';

	require_once dirname(__FILE__) . "/../../includes/config.php";
	require_once PHP_ROOTPATH.'/classes/database.php';
	$idconnect = Database::getInstance();
	$querytest = pg_query($idconnect,"SELECT * FROM droit_utilisateur WHERE (id_droit=1 or id_droit = 15)  and id_user=".$_SESSION['membre_id']);
	$saisie_transciption = pg_num_rows($querytest);
	//vérification des droits de l'utilisateur
	if(isset($_SESSION['membre_id']) &&  $saisie_transciption != 0){

		// Recuperation list d'unite
		$unitList = array();
		$query = pg_query($idconnect,"SELECT DISTINCT unite FROM resultat_test_simple");
		while ($back = pg_fetch_assoc($query)) {
			if($back["unite"] != "") {
				array_push($unitList, "<option value=\"" . $back["unite"]."\">" . $back["unite"]."</option>");
			}
		}

		// On teste si la variable de session existe et contient une valeur
		if(empty($_SESSION['id_anim'])){
			// Si inexistante ou nulle, on redirige vers le formulaire de login
			header('Location: /base_mmdn/saisie/saisie.php');
			exit();
		}
		else{
			$id_anim=$_SESSION['id_anim'];
			$code=$_SESSION['code'];
		}

		// Remplissage de la base de données
		if(!empty($_POST)){			if(empty($_POST['nom_onglet'])){
				$message = 'Veuillez sélectionner un test !';
			}
			else{
				//récupération du nom de l'onglet courant
				$onglet = htmlspecialchars($_POST['nom_onglet']);

				$date='';
				$exp='';
				$mesure='';
				$desc='';
				$unit='';
				foreach ($_POST as $cle=>$value){
					$cle=str_replace('_',' ',$cle);
					if($cle=="date $onglet"){
						$date=htmlspecialchars($value);
					}
					else if($cle=="select $onglet"){$exp=htmlspecialchars($value);}
					else if($cle=="mesure $onglet"){$mesure=htmlspecialchars($value);}
					else if($cle=="description $onglet"){$desc=htmlspecialchars($value);}
					else if($cle=="select_unite $onglet"){
						if($value != -1) {
							$unit = htmlspecialchars($value);
						}
					}
					else if($cle=="newUnite $onglet"){
						if($value != "") {
							$unit = htmlspecialchars($value);
						}
					}
				}

				if($date!='' && $exp!='' && $mesure!='' && $unit!=''){
					if(preg_match("#^\d\d\/\d\d\/\d\d\d\d$#",$date)){

						if (!empty($_POST['newTab'])) {
							$newTab = htmlspecialchars($_POST['newTab']);
							$onglet = $newTab;
						}
						//récupération de l'id_type_test
						$query = pg_query($idconnect,"SELECT id_type_test FROM type_test WHERE label LIKE '{$onglet}'");
						$back = pg_fetch_assoc($query);
						$id_type_test = $back['id_type_test'];
						if (!empty($_POST['newTab'])) {
							if (empty($id_type_test)) {
								$sql = pg_query($idconnect,"INSERT INTO type_test (label, description, unite_mesure) VALUES ('".$newTab."', NULL, NULL) RETURNING id_type_test");
								$insert_row = pg_fetch_row($sql);
								$id_type_test = $insert_row[0];
							} else {
								$message = "Erreur de saisie dans le nom d'onglet, veuillez formuler un autre nom";
								goto end; // stop insert and go to display section
							}
						}

						list($day, $month, $year) = explode("/", $date);
						$date = "{$year}-{$month}-{$day}";

						//verification de l'existante d'un test avec cet expérimentateur et cette date de test dans test pour la pesée
						$query1 = pg_query($idconnect,"SELECT id_test FROM test WHERE date_test='$date' AND experimentateur='$date'
						AND id_type_test=$id_type_test");
						$nb1 = pg_num_rows($query1);

						if($nb1!=0){ //si le test avec date et expérimentateur existe déjà
							$back1 = pg_fetch_assoc($query1);
							$id_test = $back1['id_test'];
						}
						else{ //création de test
							$sql = pg_query($idconnect,"INSERT INTO test (id_type_test,date_test,experimentateur) VALUES ($id_type_test,'$date',
							'$exp') RETURNING id_test");
							$insert_row = pg_fetch_row($sql);
							$id_test = $insert_row[0];
						}

						//vérification de l'existance de resultat_test
						$query2 = pg_query($idconnect,"SELECT id_res FROM resultat_test WHERE id_test=$id_test AND id_animal=$id_anim");
						$nb2 = pg_num_rows($query2);
						if($nb2!=0){ //si un id_res existe déjà
							$back2 = pg_fetch_assoc($query2);
							$id_res = $back2['id_res'];
						}
						else{ // création de resultat_test
							$sql = pg_query($idconnect,"INSERT INTO resultat_test (id_test,id_animal) VALUES ($id_test,$id_anim) RETURNING id_res");
							$insert_row = pg_fetch_row($sql);
							$id_res = $insert_row[0];
						}

						//vérification que resultat_test_simple est bien rempli
						$query3 = pg_query($idconnect,"SELECT mesure FROM resultat_test_simple WHERE id_res=$id_res");
						$nb3 = pg_num_rows($query3);
						if($nb3!=0){
							$back3 = pg_fetch_assoc($query3);
							if(!($back3['description']) && $desc!=''){
								$sql = pg_query($idconnect,"UPDATE resultat_test_simple SET description='$desc' WHERE id_res=$id_res");
							}
							$message = "Test déjà enregistré dans la base, mise à jour. ";
						}
						else{
							Log::logInfo($unit);
							//création ou mise à jour (modification de l'attribut description uniquement) de résultat_test_simple
							$sql = pg_query($idconnect,"INSERT INTO resultat_test_simple (id_res,mesure,unite) VALUES($id_res,'$mesure','$unit') RETURNING id_res");
							$insert_row = pg_fetch_row($sql);
							$id_res2 = $insert_row[0];
							if($desc!=''){
								$sql = pg_query($idconnect,"UPDATE resultat_test_simple SET description='$desc' WHERE id_res=$id_res2");
							}
							$message = "$onglet enregistré";
						}
					}
					else{ $message.= "Date invalide";}
				}
			}
		}
	}
	else{
		header('Location: ../../site.php');
		exit();
	}

	end:

?>

<!DOCTYPE html>
<html>
	<head>
        <meta charset="utf-8" />
        <link rel="stylesheet" href="../../style.css" />
		<!--[if lt IE 9]>
        <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
        <!--[if lte IE 7]>
        <link rel="stylesheet" href="../../style_ie.css" />
        <![endif]-->
        <title>Base de données microcèbes</title>

        <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
		<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
		<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
		<script src="../../js/date_picker.js"></script>
		<script src="../../js/oXHR.js"></script>
		<script src="../../js/verif_form.js"></script>
		<script>
		var unitlist = new Array();
		<?php
			foreach ($unitList as $unit) {
				echo "unitlist.push('$unit');\n";
			}
			unset($unitList);
		?>
		</script>
		<script src="autres_tests.js"></script>
    </head>

    <body>
		<?php include_once(dirname(dirname(dirname(__FILE__)))."/menu.php"); ?>

		<section id="main">
			<header>
				<h1>Saisie - Autres analyses animal <?php echo $code; ?></h1>
			</header>
			<?php include(dirname(dirname(__FILE__))."/menu_saisie.php"); ?>
			<section id="animal">
				<div id="menu3">
					<ul id="onglets"></ul>
				</div>
				<section id="contenu">
					<form id="contenu_onglets" method="POST" action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI'], ENT_QUOTES); ?>" onsubmit="return verif_form(this)">
						<p><label class="code2"><?php echo $message; ?></label><br/></p>
					</form>
				</section>
			</section>
		</section>
	</body>
</html>
